# -*- coding: utf-8 -*-
# @Time    : 2019/10/26 19:17
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : progress_test.py
# 多进程编程
# 多线程
# 耗cpu的操作，无法利用多核特性，无法充分利用cpu的性能
# 所以耗cpu的操作，用多进程编程，对于io操作来说，使用多线程编程
# 对于操作系统而言进程切换代价要高于线程调度
# 1. 对于耗费cpu的操作，(计算类操），多进程优于多线程
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ProcessPoolExecutor
import time


def fib(n):
    if n <= 2:
        return 1
    return fib(n - 1) + fib(n - 2)


# if __name__ == '__main__':
#     """
#     windows 下如果不放在if __name__ == '__main__':执行进程池代码，会抛出以下异常，而linux不会
#     concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
#
#     """
#     with ProcessPoolExecutor(4) as executor:
#         all_task = [executor.submit(fib, (num)) for num in range(25, 40)]
#         start_time = time.time()
#         for future in as_completed(all_task):
#             data = future.result()
#             print(f"result: {data} ")
#
#         print(f"last time is :{time.time() - start_time}")
#
#     '''
#     all_task = [executor.submit(fib, (num)) for num in range(25, 40)]
#     ProcessPoolExecutor(3): 38.00974655151367
#     ThreadPoolExecutor(20): 71.29457139968872
#     '''


# 对于io操作来说，多线程优于多进程
def random_sleep(n):
    time.sleep(n)
    return n


if __name__ == '__main__':
    '''
    模拟io操作
    '''
    with ThreadPoolExecutor(3) as executor:
        all_task = [executor.submit(random_sleep, (num)) for num in [2]*30]
        start_time = time.time()
        for future in as_completed(all_task):
            data = future.result()
            print(f"result: {data} ")

        print(f"last time is :{time.time() - start_time}")